<template>
  <div>
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-input 
      v-model="nameSearch" 
      placeholder="请输入姓名搜索"
      style="width: 200px; margin-bottom: 10px;"
    ></el-input>
    <el-input 
      v-model="sexSearch" 
      placeholder="请输入性别搜索"
      style="width: 200px; margin-bottom: 10px;"
    ></el-input>
    <el-table :data="filteredTableData" border>
  <el-table-column prop="name" label="姓名"></el-table-column>
  <el-table-column prop="age" label="年龄"></el-table-column>
  <el-table-column prop="sex" label="性别"></el-table-column>
  <el-table-column label="操作">
    <template #default="scope">
      <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
      <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
    </template>
  </el-table-column>
</el-table>

   
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="form.sex"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref ,computed} from "vue";
const nameSearch = ref("");
const sexSearch = ref("");

const tableData = ref([
  { name: "张三", age: 20, sex: "男" },
  { name: "李四", age: 25, sex: "女" },
]);
const filteredTableData = computed(() => {
  return tableData.value.filter(item => {
    const matchesName = item.name.includes(nameSearch.value);
    const matchesSex = item.sex.includes(sexSearch.value);
    return matchesName && matchesSex;
  });
});
const dialogVisible = ref(false);
const dialogTitle = ref("新增");
const form = ref({
  name: "",
  age: "",
});
let editIndex = -1;
const handleAdd = () => {
  dialogTitle.value = "新增";
  form.value = { name: "", age: "" };
  editIndex = -1;
  dialogVisible.value = true;
};
const handleEdit = (index, row) => {
  dialogTitle.value = "编辑";
  form.value = { ...row };
  editIndex = index;
  dialogVisible.value = true;
};
const handleDelete = (index, row) => {
  tableData.value.splice(index, 1);
};
const handleSubmit = () => {
  if (editIndex === -1) {
    tableData.value.push({ ...form.value });
  } else {
    tableData.value[editIndex] = { ...form.value };
  }
  dialogVisible.value = false;
};
</script>
